<template>
  <div class="guiji-page" v-loading="timerLoading">
    <div class="nav-wrap">
      <div class="nav-top">
        <span style="color: #333;font-size: 12px;font-weight:bold;margin-left: 20px">轨迹回放</span>
        <span style="color: #333;font-size: 13px;margin-left: 20px">{{ carNo }}(设备号:{{ deviceNo }})</span>
        <div style="flex: 1"></div>
        <span class="refresh-icon" @click="goTrace"
              style="margin-right: 20px;background: white;font-size: 12px;padding: 5px;cursor: pointer">实时跟踪</span>
      </div>

      <div class="nav-center">
        <el-date-picker @change="onChange" size="mini" :picker-options="pickerOptions"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        v-model="adsadasdsadsadsa" type="datetimerange" range-separator="-" start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>

        <span style="font-size: 14px;color: #676767;margin-left: 20px">定位方式：</span>
        <el-select size="mini" multiple v-model="loctype" placeholder="请选择">
          <el-option
            label="卫星定位"
            value="1">
          </el-option>
          <el-option
            label="基站定位"
            value="2">
          </el-option>
          <el-option
            label="WIFI定位"
            value="3">
          </el-option>
        </el-select>

        <el-button type="primary" @click="locTypeChange" size="mini" style="margin-left: 20px">确定</el-button>

        <div style="flex: 1"></div>

        <span style="font-size: 14px;color: #676767;margin-left: 20px">停留标记：</span>
        <el-select size="mini" clearable v-model="timerange" placeholder="请选择" @change="stayPoint">
          <el-option
            label="10分钟"
            value="600">
          </el-option>
          <el-option
            label="15分钟"
            value="900">
          </el-option>
          <el-option
            label="30分钟"
            value="1800">
          </el-option>
          <el-option
            label="45分钟"
            value="2700">
          </el-option>
          <el-option
            label="1小时"
            value="3600">
          </el-option>
          <el-option
            label="2小时"
            value="7200">
          </el-option>
          <el-option
            label="6小时"
            value="21600">
          </el-option>
          <el-option
            label="12小时"
            value="43200">
          </el-option>
          <el-option
            label="24小时"
            value="86400">
          </el-option>
        </el-select>

        <el-button size="mini" style="margin-left: 20px" @click="showTrace">轨迹明细</el-button>
      </div>

      <div class="nav-bottom">

        <i @click="reset" style="font-size: 25px;margin-left: 50px"
           :class="play?'el-icon-video-pause':'el-icon-video-play'"></i>

        <div style="display: flex;flex-direction: column" class="block step-wrap">
          <el-slider
            @input="inputChangeStep"
            v-model="stepindex" :step="1" :max="pointList.length" :min="1" :show-tooltip="false">
          </el-slider>

          <div style="display: flex;align-items: center">
            <div class="block speed-wrap">
              <el-slider v-model="speed" :step="1000" :max="10000" :min="1000" :show-tooltip="false">
              </el-slider>
            </div>
            <span class="speed-text">速度：x{{ speed / 1000 }}</span>
          </div>
        </div>

        <span class="gpsTime">{{ stepItem.gpsTime }}</span>

        <i class="el-icon-refresh-right refresh-icon" @click="restart"></i>

        <span v-if="false" class="refresh-icon" style="font-size: 12px;background: white">切换至打点播放</span>

        <span style="font-size: 12px;color: #676767;margin-left: 20px;width: 170px">总里程：{{
            totalMileage
          }} km 速度：{{ stepItem.gpsSpeed || '--' }}KM/H</span>

        <i class="el-icon-location" style="color: #3b9cd5;margin-left: 70px"></i>
        <span style="font-size: 12px;color: #676767;margin-left: 5px">卫星</span>
        <i class="el-icon-location" style="color: #e17913;margin-left: 20px"></i>
        <span style="font-size: 12px;color: #676767;margin-left: 5px">基站</span>
        <i class="el-icon-location" style="color: #418f02;margin-left: 20px"></i>
        <span style="font-size: 12px;color: #676767;margin-left: 5px">WIFI</span>
      </div>

    </div>
    <baidu-map @ready="handlerBMap" class="map" :zoom="13" :scroll-wheel-zoom="true">
      <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
      <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-map-type>
      <bm-scale anchor="BMAP_ANCHOR_BOTTOM_LEFT"></bm-scale>

      <bm-marker v-for="(item, index) in stayList" :key="index" :position="{lng: item.lng, lat: item.lat}"></bm-marker>

      <bm-polyline :path="path" stroke-color="blue" :stroke-opacity="0.3" :stroke-weight="5"></bm-polyline>

      <!--      :content="mInfo"-->
      <bml-lushu
        @stop="reset" :path="path"
        :icon="icon" :autoView="true"
        :infoWindow="showInfoWindow"
        :content="mInfo"
        @move="move"
        @finish="finish"
        :moveToIndex="moveToIndex"
        :rotation="true" :speed="speed"
        :play="play">

<!--        <bm-info-window ref="infoWindow" :position="{lng: stepItem.lng, lat: stepItem.lat}" :show="true">-->
<!--          <div>弄不成放弃了</div>-->
<!--        </bm-info-window>-->

      </bml-lushu>



    </baidu-map>

    <div class="bottom-row" v-if="showDetail">
      <div class="bottom-top">
        <h5>轨迹明细</h5>
        <i class="el-icon-close" @click="showDetail=false"></i>
      </div>

      <div class="bottom-title">
        <tr class="list-title">
          <td width="60">序号</td>
          <td width="140">定位时间</td>
          <td width="140">接收时间</td>
          <td width="300">经度/纬度</td>
          <td width="100">速度(km/h)</td>
          <td width="130">方向</td>
          <td width="90">定位类型</td>
          <td width="160">上报模式</td>
          <td>位置</td>
        </tr>

      </div>

      <div class="bottom-content">
        <tr :id="'tr'+index" :style="{'background-color':index===stepindex?'#FFE6B0':'#fff'}" class="list-title2"
            v-for="(item, index) in pointList" :key="index">
          <td width="60">序号{{ index + 1 }}</td>
          <td width="140">{{ item.gpsTime }}</td>
          <td width="140">{{ item.gpsTime }}</td>
          <td width="300">{{ item.lat }}/{{ item.lng }}</td>
          <td width="100">{{ item.gpsSpeed || '--' }}KM/H</td>
          <td width="130">{{ directionText(item.direction) }}(方向数：{{ item.direction || '--' }})</td>
          <td width="90">
            {{ '1' === item.posType ? '卫星定位' : '2' === item.posType ? '基站定位' : '3' === item.posType ? 'wifi定位' : '--' }}
          </td>
          <td width="160">定时上报</td>
          <td :style="{color: item.address?'#666':'#0d65eb'}" @click="getRealAddress(item)">
            {{ item.address ? item.address : '点击获取地址' }}
          </td>
        </tr>
      </div>


    </div>

  </div>
</template>

<script>
import * as MmvApi from '@/api/mmv'
import {BMap, BmlLushu} from '@/components/vue-baidu-map';
import _ from 'lodash';
import data from './components/data.json'
import {v4} from 'uuid'

export default {
  components: {
    BmlLushu,
  },
  data() {
    return {
      moveToIndex: -1,
      stepItem: {},
      deviceItem: {},
      totalMileage: 0,
      play: false,
      stepindex: 0,
      speed: 1000,
      icon: {
        url: 'http://api.map.baidu.com/library/LuShu/1.2/examples/car.png',
        size: {width: 52, height: 26},
        opts: {anchor: {width: 27, height: 13}}
      },
      path: [],
      pointList: [],
      originData: [],//原始数据
      adsadasdsadsadsa: [],
      pickerOptions: {
        // disabledDate: (time) => {
        //     const now = new Date(time).getTime();
        //     const min = new Date(this.qqqqqqqq[0]).getTime() - 100;
        //     const max = new Date(this.qqqqqqqq[1]).getTime() + 100;
        //     if (now < min || now > max) {
        //         return true
        //     }
        //     console.log(min, now, max);
        //     return false;
        // },
      },
      loctype: [],
      showDetail: false,
      timerange: '',
      showInfoWindow: false,
      mInfo: `<div class="info-window">
                <div>
                    <span >序号:</span>
                    <span id="id0">0</span>
                </div>

                <div>
                    <span >定位类型:</span>
                    <span id="id1"></span>
                </div>

                <div>
                    <span >速度:</span>
                    <span id="id3"></span>
                </div>

                <div>
                    <span >定位地点:</span>
                    <span id="id4" style="'color':'#0d65eb'">点击查看地址</span>
                </div>
              </div>`,
      deviceNo: '',
      manufacturer: '',
      stayList: [],
      carNo:'',
      simNo:'',
      timerLoading:false
    }
  },
  computed: {
    playBtnText() {
      return this.play ? '暂停' : '播放'
    },
  },

  created() {
    const {query} = this.$route;

    // this.$router.push({ query: {} });
    this.adsadasdsadsadsa = [query.aaa, query.bbb];
    this.deviceNo = query.deviceNo;
    this.manufacturer = query.manufacturer;
    this.carNo = query.carNo;
    this.simNo = query.simNo;
    this.totalMileage = query.totalMileage || 0;
    this.deviceItem = JSON.parse(query.deviceItem) || {};
  },
  mounted() {
    setTimeout(() => {
      this.play = true
    }, 2000)

    // setTimeout(() => {
    //   console.log('infowindow==>', document.getElementById('id4'))
    //
    //   let aaa = document.getElementById('id4')
    //   aaa.onclick = function(){
    //     console.log('点我干嘛？')
    //   }
    //
    // }, 5000)
  },
  methods: {
    finish(e) {
      this.$confirm(`回放完毕，行驶${this.totalMileage}KM`, '提示', {
        confirmButtonText: '重播',
        cancelButtonText: '确定',
        type: 'success'
      }).then(() => {
        this.moveToIndex=0
        this.play = !this.play;
      }).catch(() => {
        this.moveToIndex = e.index
      });
    },
    goTrace(){
      let routeUrl = this.$router.resolve({
        path: '/map-trace',
        // query: {nowCarNo: this.carNo},
        query: { deviceItem: JSON.stringify(this.deviceItem) },
      })
      window.open(routeUrl.href, '_blank')
    },
    reset() {

      this.play = !this.play;
      if(this.play && this.moveToIndex===this.pointList.length-1){
        this.moveToIndex=0
      }
    },
    inputChangeStep(e){
      this.moveToIndex = e+1
    },
    move(e) {
      // console.log('路书正在进行……', e)
      this.stepindex = e.index
      this.stepItem = this.pointList[e.index]

      // document.getElementById('id0').innerHTML = this.stepindex

      this.scrollTr()
    },
    showTrace() {
      this.showDetail = !this.showDetail

      this.$nextTick(()=>{
        this.scrollTr()
      })
    },
    scrollTr() {
      let idName = `tr${this.stepindex}`
      document.getElementById(idName) && document.getElementById(idName).scrollIntoView({
        block: "center",
        behavior: "auto",
        inline: "start"
      });

    },
    stayPoint() {
      if (this.timerange && this.timerange > 0) {
        this.stayList = this.pointList.filter(item => item.dwellTime >= this.timerange)
      } else {
        this.stayList = []
      }
    },

    locTypeChange() {
      let that = this

      if (this.loctype.length <= 0) {
        this.pointList = this.originData
      } else {
        this.pointList = this.originData.filter(item => {
          if (that.loctype.includes(item.posType)) {
            return item
          }
        });
      }


      /* if (query.aaa) {
           path = path.filter(val => new Date(val.gpsTime).getTime() > new Date(Number(query.aaa)).getTime());
       }
       if (query.bbb) {
           path = path.filter(val => new Date(val.gpsTime).getTime() < new Date(Number(query.bbb)).getTime());
       }*/
      this.path = this.pointList.map(val => {
        return new this.BMap.Point(val.lng, val.lat);
      });
      if (this.path.length === 0) {
        this.$message.warning('暂无轨迹')
      }

      this.stepindex = 0

      this.$forceUpdate()

    },

    getRealAddress(item) {
      let that = this;
      let pt = new this.BMap.Point(item.lng, item.lat);
      let myGeo = new this.BMap.Geocoder();
      myGeo.getLocation(pt, function (result) {
        item.address = result.address

        that.$forceUpdate()
      });

    },
    directionText(direction) {

      if (direction <= 10) {
        return '正北向'
      } else if (direction <= 80) {
        return '东北向'
      } else if (direction <= 100) {
        return '正东向'
      } else if (direction <= 170) {
        return '东南向'
      } else if (direction <= 190) {
        return '正南向'
      } else if (direction <= 260) {
        return '西南向'
      } else if (direction <= 280) {
        return '正西向'
      } else if (direction <= 350) {
        return '西北向'
      } else {
        return '正北向'
      }

    },
    onChange() {

      let _this = this
      this.timerLoading = true
      MmvApi.getTrack({
        deviceNo: this.deviceNo,
        trackStartTime: this.adsadasdsadsadsa[0],
        trackEndTime: this.adsadasdsadsadsa[1],
        manufacturer: this.manufacturer
      }).then((response) => {
        this.timerLoading = false
        const trackPath = response.data.trackPlayList || []

        const id = v4()
        sessionStorage.setItem(id, JSON.stringify(trackPath))

        const {path, query} = this.$route
        _this.$router.push({
          path, query: {
            id: id,
            aaa: _this.adsadasdsadsadsa[0],
            bbb: _this.adsadasdsadsadsa[1],
            deviceNo: _this.deviceNo,
            manufacturer: _this.manufacturer,
            totalMileage: response.data.totalMileage,
            carNo:_this.carNo,
            simNo: _this.simNo
          }
        });
        window.location.reload()

      }).catch((err) => {
        this.timerLoading = false
        this.$message.error('暂无轨迹')
      })

    },

    restart() {
      const {path, query} = this.$route
      this.$router.push({
        path, query: {
          id: this.$route.query.id,
          aaa: this.adsadasdsadsadsa[0],
          bbb: this.adsadasdsadsadsa[1],
          deviceNo: this.deviceNo,
          manufacturer: this.manufacturer,
          totalMileage: response.data.totalMileage,
          carNo:_this.carNo,
          simNo: _this.simNo
        }
      });
      window.location.reload()
    },

    handlerBMap({BMap, map}) {
      const {query} = this.$route
      this.BMap = BMap;
      this.map = map;
      this.originData = JSON.parse(sessionStorage.getItem(this.$route.query.id)) ?? [];
      this.pointList = this.originData;
      /* if (query.aaa) {
           path = path.filter(val => new Date(val.gpsTime).getTime() > new Date(Number(query.aaa)).getTime());
       }
       if (query.bbb) {
           path = path.filter(val => new Date(val.gpsTime).getTime() < new Date(Number(query.bbb)).getTime());
       }*/
      this.path = this.pointList.map(val => {
        return new this.BMap.Point(val.lng, val.lat);
      });
      if (this.path.length === 0) {
        this.$message.warning('暂无轨迹')
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.guiji-page {
  display: flex;
  position: relative;
}

.info-window {
  //height: 190px;
  border-radius: 4px;
  border: 1px solid #333;
}

.info-head {
  height: 26px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f9f9f9;
  border-bottom: 1px solid #ddd;
  border-radius: 4px 4px 0 0;
  padding: 0 20px;
}

.info-content {
  display: flex;
  //justify-content: center;
}

.info-left {
  width: 80px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;

}

.nav-wrap {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
  display: flex;
  flex-direction: column;
}

.nav-top {
  height: 42px;
  display: flex;
  align-items: center;
  background-color: aliceblue;
  background-image: linear-gradient(#F1F5FD, #E9F0FF);
  box-shadow: inset 0 1px 0 #fff;;
  border-bottom: 1px solid #ddd;
}

.nav-center {
  height: 51px;
  background: #fff;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  padding: 0 20px;
}

.nav-bottom {
  width: 1000px;
  height: 56px;
  border-radius: 0 0 50px 50px;
  border: 1px solid #ddd;
  background: white;
  border-top: 0;
  align-self: center;
  -webkit-box-shadow: 0px 1px 4px -1px rgb(0 0 0 / 30%);
  display: flex;
  align-items: center;
}

.speed-text {
  margin-left: 10px;
  width: 58px;
  font-size: 12px;
  color: #676767;
}

.gpsTime {
  width: 118px;
  margin-left: 10px;
  font-size: 12px;
  color: #676767;
}

.step-wrap {
  width: 180px;
  margin: 0 10px;
}

.speed-wrap {
  width: 80px;
  margin: 5px 10px 0 0;
}

.refresh-icon {
  margin-left: 10px;
  padding: 2px;
  border: 1px solid #adadad;
  color: #333;
  background-color: #e6e6e6;
  font-size: 13px;
}

::v-deep .el-slider__runway {
  margin: 5px 0;
}

.map {
  /*width: calc(100vw - 320px);*/
  width: 100vw;
  height: 100vh;
  /*margin-top: 93px;*/
}

::v-deep .BMap_stdMpType0 .BMap_stdMpZoom, .BMap_stdMpType1 .BMap_stdMpZoom, .BMap_stdMpType4 .BMap_stdMpZoom, .BMap_stdMpType3 .BMap_stdMpZoom {
  top: 130px;
}

::v-deep .anchorTR {
  top: 130px !important;
}

.bottom-row {
  height: 213px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
}

.bottom-top {
  height: 37px;
  display: flex;
  align-items: center;
  background-color: aliceblue;
  background-image: linear-gradient(#F1F5FD, #E9F0FF);
  border-bottom: 1px solid #ddd;
  box-shadow: 0 0 3px rgba(0, 0, 0, .2);
  justify-content: space-between;

  h5 {
    padding: 10px;
    font-weight: bold;
    color: #666;
  }

  i {
    border: 1px solid #ccc;
    padding: 10px;
    font-weight: bold;
    color: #666;
  }
}

.bottom-title {

}

.list-title {
  display: flex;
  align-items: center;
  margin-left: 10px;
  height: 27px;
  border-bottom: 1px solid #ececec;

  td {
    font-size: 12px;
    color: #666;
    font-weight: bold;
  }
}

.bottom-content {
  overflow: scroll;
  max-height: 149px;
  overflow-x: hidden;

  .list-title2 {
    display: flex;
    align-items: center;
    padding-left: 10px;
    height: 27px;
    border-bottom: 1px solid #ececec;

    td {
      font-size: 12px;
      color: #666;
    }
  }
}

</style>
